#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include "process.h"



Process::Process(std::string file) : file(file)
{
}

Process::~Process()
{
}

void Process::addParameter(std::string parameter)
{
    parameters.push_back(parameter);
}

void Process::execute()
{
    // construct argv
    int argc = parameters.size() + 2;
    char** argv = new char*[argc];
	argv[0] = new char[file.length()];
	strcpy(argv[0], file.c_str());

	int n = 1;
	for (std::vector<std::string>::iterator i=parameters.begin(); i!=parameters.end(); ++i, ++n)
	{
		argv[n] = new char[(*i).length()];
		strcpy(argv[n], (*i).c_str());
	}

    argv[argc-1] = 0;

    // execute the process
    pid_t pid;
    switch (pid = fork())
    {
		case -1:
			std::cerr << "fork failed\n";
		break;
		case 0: // child
			execvp(argv[0], argv);
			std::cerr << "shell: " << argv[0] << ": command not found\n";
		break;
		default: // parent
			int status;
			while (wait(&status) >= 0);
		break;
    }

    delete[] argv;
}
